<template>
  <div class="container mx-auto p-4">
    <app-header class="mb-4"/>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="flex flex-col items-center justify-center py-12">
      <svg class="animate-spin h-10 w-10 text-blue-500 mb-4" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
      </svg>
      <p class="text-gray-600 text-lg">加载中...</p>
    </div>
    
    <!-- 未找到日志 -->
    <div v-else-if="!log" class="flex flex-col items-center justify-center py-12 bg-white rounded-lg shadow-md">
      <svg xmlns="http://www.w3.org/2000/svg" class="h-16 w-16 text-gray-400 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
      </svg>
      <p class="text-gray-600 text-lg">未找到日志记录</p>
    </div>
    
    <!-- 日志详情 -->
    <div v-else>
      <div class="bg-white rounded-lg shadow-md overflow-hidden">
        <!-- 基本信息 -->
        <div class="p-6 border-b border-gray-200">
          <h2 class="text-xl font-bold text-gray-800 mb-4">基本信息</h2>
          <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div class="space-y-3">
              <div class="flex items-center">
                <span class="font-medium text-gray-600 w-24">ID:</span> 
                <span class="text-gray-900">{{ log.id }}</span>
              </div>
              <div class="flex items-center">
                <span class="font-medium text-gray-600 w-24">时间:</span> 
                <span class="text-gray-900">{{ formatDate(log.timestamp) }}</span>
              </div>
              <div class="flex items-center">
                <span class="font-medium text-gray-600 w-24">事件类型:</span> 
                <span class="px-2 py-1 text-xs font-semibold rounded-full" :class="getEventTypeClass(log.event_type)">
                  {{ log.event_type }}
                </span>
              </div>
            </div>
            <div class="space-y-3">
              <div class="flex items-center">
                <span class="font-medium text-gray-600 w-24">结果:</span> 
                <span class="px-2 py-1 text-xs font-semibold rounded-full" 
                      :class="isPass(log.result) ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'">
                  {{ isPass(log.result) ? 'PASS' : 'FAIL' }}
                </span>
              </div>
              <div class="flex items-start">
                <span class="font-medium text-gray-600 w-24 mt-1">消息:</span> 
                <span class="text-gray-900">{{ log.message || '无' }}</span>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 请求数据 -->
        <div class="p-6 border-b border-gray-200">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-gray-800">请求数据</h2>
            <button @click="copyToClipboard(formatJson(log.request_data))" 
                    class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors duration-200 text-sm flex items-center">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
              </svg>
              复制
            </button>
          </div>
          <pre class="bg-gray-50 p-4 rounded-lg overflow-x-auto text-sm border border-gray-200">{{ formatJson(log.request_data) }}</pre>
        </div>
        
        <!-- 响应数据 -->
        <div class="p-6">
          <div class="flex justify-between items-center mb-4">
            <h2 class="text-xl font-bold text-gray-800">响应数据</h2>
            <button @click="copyToClipboard(formatJson(log.response_data))" 
                    class="px-3 py-1 bg-gray-200 text-gray-700 rounded hover:bg-gray-300 transition-colors duration-200 text-sm flex items-center">
              <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
              </svg>
              复制
            </button>
          </div>
          <pre class="bg-gray-50 p-4 rounded-lg overflow-x-auto text-sm border border-gray-200">{{ formatJson(log.response_data) }}</pre>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getMesLogById } from '@/api/mesLogs'
import AppHeader from '@/components/AppHeader.vue';

export default {
  name: 'MesLogDetail',
  components: {AppHeader},
  
  setup() {
    const route = useRoute()
    const router = useRouter()
    const log = ref(null)
    const loading = ref(true)
    
    // 格式化 JSON
    const formatJson = (jsonStr) => {
      if (!jsonStr) return '{}'
      try {
        const obj = typeof jsonStr === 'string' ? JSON.parse(jsonStr) : jsonStr
        return JSON.stringify(obj, null, 2)
      } catch (e) {
        return jsonStr
      }
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    }
    
    // 获取事件类型的样式
    const getEventTypeClass = (eventType) => {
      switch(eventType) {
        case 'SN_CheckIn':
          return 'bg-blue-100 text-blue-800';
        case 'SN_CheckOut':
          return 'bg-purple-100 text-purple-800';
        default:
          return 'bg-gray-100 text-gray-800';
      }
    }
    
    // 判断结果是否为通过
    const isPass = (result) => {
      // 处理不同类型的结果值
      if (result === true || result === 1 || result === '1' || result === 'PASS' || result === 'true') {
        return true;
      }
      return false;
    }
    
    // 复制到剪贴板
    const copyToClipboard = (text) => {
      navigator.clipboard.writeText(text)
        .then(() => {
          alert('已复制到剪贴板');
        })
        .catch(err => {
          console.error('复制失败:', err);
        });
    }
    
    // 加载日志详情
    const loadLogDetail = async () => {
      try {
        loading.value = true
        const id = parseInt(route.params.id)
        if (isNaN(id)) {
          console.error('无效的日志ID')
          return
        }
        
        log.value = await getMesLogById(id)
      } catch (error) {
        console.error('加载日志详情失败:', error)
      } finally {
        loading.value = false
      }
    }
    
    onMounted(() => {
      loadLogDetail()
    })
    
    return {
      log,
      loading,
      formatJson,
      formatDate,
      getEventTypeClass,
      isPass,
      copyToClipboard
    }
  }
}
</script>
